package server_common

import (
	"context"
	"google.golang.org/grpc"
	"grpc_demo/conf"
	"grpc_demo/pkg/logger"
	pb "grpc_demo/proto_gen"
	"log"
	"net"
	"strconv"
	"time"
)

type server struct {
	pb.UnimplementedGreeterServer
}

func InitRpcServer(ctx context.Context) func() {
	lis, err := net.Listen("tcp", ":"+strconv.Itoa(conf.ConfigInstance.Server.Port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	go func() {
		pb.RegisterGreeterServer(s, &server{})
		logger.WithContext(ctx).Infof("server listening at %v", lis.Addr())
		if err := s.Serve(lis); err != nil {
			logger.WithContext(ctx).Fatalf("failed to serve: %v", err)
		}
	}()
	return func() {
		time.Sleep(1 * time.Second)
		stop := s.Stop
		defer stop()
	}
}
